package com.example.itcacp.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.itcacp.entity.User;
import com.example.itcacp.exception.CustomerException;
import com.example.itcacp.repository.mybatis.UserMapper;
import com.example.itcacp.service.UserService;
import com.example.itcacp.util.TokenUtils;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
//import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;


/**
 *
 * UserService实现类：用户服务接口实现
 * */
//MyBatis-Plus --- 继承ServiceImpl<UserMapper, User>涵盖基本CRUD方法 --- 业务逻辑实现
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    //依赖注入
    @Resource
    private UserMapper userMapper;

    @Value("${image.upload.path}")
    private String uploadPath;

    @Value("${server.address}")
    private String serverAddress;

    //登录
    @Override
    public User login(User user){
        //1. 验证账号是否存在，验证角色信息
        User dbuser = userMapper.selectUserWithRoleByUsername ( user.getUsername () );
        if (dbuser == null) {
            throw new CustomerException ("账号不存在");
        }
        // 密码验证（使用Spring Security的密码匹配器）
        PasswordEncoder encoder = new BCryptPasswordEncoder ();
        if (!encoder.matches(user.getPassword(), dbuser.getPassword())) { // 对比明文和加密密码
            throw new CustomerException("账号或密码错误");
        }
        // 生成token
        String token = TokenUtils.createToken ( dbuser.getUser_id () + "-" + dbuser.getRole().getRoleName() );
        dbuser.setToken ( token );
        return dbuser;
    }

    //注册
    @Override
    public void register(User user) {
        // 1. 根据新的账号查询数据库  是否存在同样账号的数据
        User dbUser = userMapper.selectByUsernameUser(user.getUsername());
        if (dbUser != null) {
            throw new CustomerException ("账号已存在");
        }
        //2. 密码加密（使用Spring Security的PasswordEncoder）;
        PasswordEncoder encoder = new BCryptPasswordEncoder ();
        String encodedPassword = encoder.encode(user.getPassword()); // 加密密码
        user.setPassword(encodedPassword); // 设置加密后的密码
        user.setPassword ( user.getPassword () );
        // 3. 其余默认项设置
        user.setUsername ( user.getUsername () );
        user.setEmail ( user.getEmail () );
        user.setRole_id ( 2L );
        user.setProfile_photo_path("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"); // 默认为黑白图像
            //设置系统当前时间为创建时间
        user.setCreated_at ( new Timestamp ( System.currentTimeMillis () ).toLocalDateTime () );
        // 4. 插入数据库
        userMapper.insert( user );
    }

    // 用户更新数据
    @Override
    public void updateprofile(User user) {
        user.setUpdated_at (new Timestamp ( System.currentTimeMillis () ).toLocalDateTime ()  );
        userMapper.updateById ( user );
    }
    // 图像上传
    @Override
    @Transactional
    public User uploadProfilePhoto(String user_id, MultipartFile file) throws IOException {
        // 获取用户信息（用户必须存在才能更新头像）
        User dbuser = userMapper.findById ( user_id );
        System.out.println (dbuser);
        if (dbuser == null) {
            throw new CustomerException("账户不存在");
        }
        // 生成唯一文件名
        String originalFileName = file.getOriginalFilename();
        String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID() + fileExtension;
        // 构建文件存储路径（确保目录存在）
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
        Path filePath = uploadDir.resolve(uniqueFileName);
        // 保存文件到服务器
        Files.write(filePath, file.getBytes());
        // 生成可访问的图片URL（注意端口和路径匹配前端需求）
        String imageUrl = "http://" + serverAddress + ":" + 8000 + "/avatar/" + uniqueFileName;
        dbuser.setProfile_photo_path(imageUrl);
        dbuser.setUpdated_at (new Timestamp ( System.currentTimeMillis () ).toLocalDateTime ()  );
        // 更新数据库中的头像路径
        userMapper.updateById(dbuser);
        return userMapper.findById ( user_id );
    }

    @Override
    public User searchUsers(String keyword) {
        return userMapper.selectByUsernameUser ( keyword );
    }

    @Override
    public User getUser(String userId) {
        return userMapper.findById ( userId );
    }
}


